package com.example.java_gobang.game;

import com.example.java_gobang.model.MatchResponse;
import com.example.java_gobang.model.Room;
import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@Component
public class Matcher {
    private Queue<User> normalQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private RoomManager roomManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    public void add(User user) {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.offer(user);
                normalQueue.notify();
                startTimer(normalQueue, 2000);
            }
            log.info("把玩家 " + user.getUsername() + " 加入到了normalQueue中");
        } else if (user.getScore() >= 2000 && user.getScore() <= 3000) {
            synchronized (highQueue){
                highQueue.offer(user);
                highQueue.notify();
                startTimer(highQueue, 2000);
            }
            log.info("把玩家 " + user.getUsername() + " 加入到了highQueue中");
        } else {
            synchronized (veryHighQueue) {
                veryHighQueue.offer(user);
                veryHighQueue.notify();
                startTimer(veryHighQueue, 2000);
            }
            log.info("把玩家 " + user.getUsername() + " 加入到了veryHighQueue中");
        }
    }
    private void startTimer(Queue<User> matchQueue, int score) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                synchronized (matchQueue) {
                    if (matchQueue.size() == 1) {
                        User bot = createBotUser(score);
                        matchQueue.offer(bot);
                        matchQueue.notify();
                        log.info("添加机器人玩家到队列中：" + bot.getUsername());
                    }
                }
            }
        }, 5000);
    }
    private User createBotUser(int score) {
        User bot = new User();
        bot.setUserId(-1); // 设置特殊ID，表示这是一个机器人
        bot.setUsername("Bot" + System.currentTimeMillis());
        bot.setScore(score);
        return bot;
    }

    public void remove(User user) {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.remove(user);
            }
            log.info("把玩家 " + user.getUsername() + " 从normalQueue中删除");
        } else if (user.getScore() >= 2000 && user.getScore() <= 3000) {
            synchronized (highQueue) {
                highQueue.remove(user);
            }
            log.info("把玩家 " + user.getUsername() + " 从highQueue中删除");
        } else {
            synchronized (veryHighQueue) {
                veryHighQueue.remove(user);
            }
            log.info("把玩家 " + user.getUsername() + " 从veryHighQueue中删除");
        }
    }

    public Matcher() {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(normalQueue);
                }
            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(highQueue);
                }
            }
        };
        t2.start();

        Thread t3 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(veryHighQueue);
                }
            }
        };
        t3.start();
    }

    private void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue) {
            try {
                while (matchQueue.size() < 2) {
                    matchQueue.wait();
                }
                User player1 = matchQueue.poll();
                User player2 = matchQueue.poll();
                boolean isBot = false;
                if (player2.getUserId() == -1) {
                    isBot = true;
                }
                log.info("匹配出两个玩家：" + player1.getUsername() + ", " + player2.getUsername());

                WebSocketSession session1 = onlineUserManager.getFromGameHall(player1.getUserId());
                //判断特殊情况
                if (session1 == null) {
                    matchQueue.offer(player2);
                    return;
                }
                if (isBot) {
                    log.info("匹配机器人");
                    Room room = new Room();
                    room.setUser1(player1);
                    room.setUser2(player2);
                    room.setWhiteUserId(player1.getUserId());
                    roomManager.add(room, player1.getUserId(), player2.getUserId());
                    //给玩家反馈信息： 你匹配到人机了
                    //通过websocket返回一个message 为 ‘matchSuccess’ 响应
                    MatchResponse response = new MatchResponse();
                    response.setOk(true);
                    response.setMessage("matchRobot");
                    session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                } else {
                    WebSocketSession session2 = onlineUserManager.getFromGameHall(player2.getUserId());

                    //判断特殊情况
                    if (session2 == null) {
                        matchQueue.offer(player1);
                        return;
                    }
                    if (session1 == session2) {
                        matchQueue.offer(player1);
                        return;
                    }
                    //把玩家加入房间
                    Room room = new Room();
                    roomManager.add(room, player1.getUserId(), player2.getUserId());

                    //给玩家反馈信息： 你匹配到对手了
                    //通过websocket返回一个message 为 ‘matchSuccess’ 响应
                    MatchResponse response = new MatchResponse();
                    response.setOk(true);
                    response.setMessage("matchSuccess");
                    session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                    session2.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                }

            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
